import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/rawKeyboardListener/KqRawKeyboardListener.dart';
import '../../resources/kq_theme_colors.dart';
import '../../resources/l10n/kq_intl.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_widgets/theme/kq_theme_manager.dart';
import 'package:kq_flutter_widgets/widgets/divider/kq_divider.dart';

import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../textFiled/kq_textfiled.dart';

/// 通用搜索栏
///
/// @author 周卓
///
class KqSearchBar extends StatefulWidget {
  /// 提示文字
  final String? hintText;

  /// 是否可以编辑
  final bool editable;

  /// 是否自动聚焦
  final bool autofocus;

  /// 自定义水平padding left，默认16.r
  final double? paddingLeft;

  /// 自定义水平padding right，默认16.r
  final double? paddingRight;

  /// 取消按钮是否启用
  final bool cancelBtnEnable;

  /// 是否一直显示取消按钮，默认false
  final bool alwaysShowCancelBtn;

  /// 当[editable]=false时,是否自动聚焦边框
  final bool autoFocusBorder;

  /// 自定义搜索左侧图标
  final Widget? customLeftIcon;

  /// 左侧搜索图标的颜色
  final Color? searchIconColor;

  /// 是否显示下端分割线
  final bool showDivider;

  /// 字体大小
  final double? fontSize;

  /// 新的搜索值，一般用来还原上次的搜索内容
  final String? newValue;

  /// 外层背景颜色，默认白色
  final Color? outerBgColor;

  /// 里层背景颜色，默认灰色
  final Color? innerBgColor;

  /// 输入框光标颜色
  final Color? cursorColor;

  /// 输入框文字颜色
  final Color? textColor;

  /// 取消按钮文字颜色
  final Color? cancelTextColor;

  /// 提示文字颜色
  final Color? placeHolderTextColor;

  /// 不可编辑时点击回调
  /// 需要焦点时，调用 [state.requestFocus()]
  final Function(KqSearchBarState state)? onTap;

  /// 文字控制器
  final TextEditingController? editController;

  /// 自定义搜索框左边控件
  final Widget? customLeftWidget;

  /// 自定义搜索框右侧控件
  final Widget? customRightWidget;

  /// 搜索回调（包括扫码枪和软键盘的提交）
  final Function(String value, KqSearchBarState state)? onSubmit;

  /// 用于监听停顿回调，基于onTextChange，500ms没有输入则回调，避免频繁调用接口。
  final Function(String str)? onMonitor;

  /// 数值变化监听
  final ValueChanged<String>? onChanged;

  /// 清空按钮点击监听
  final VoidCallback? onCleared;

  /// 是否启动PDA扫码，默认不启用
  final bool enablePDAScan;

  /// 点击清空按钮是否自动移除焦点和收起键盘
  final bool unFocusWhenCleared;

  /// 取消回调
  final Function()? onCancel;

  /// 外层整体高度，默认44.r
  final double? outHeight;

  /// 内层搜索框部分高度，默认30.r
  final double? innerHeight;

  /// 取消按钮提示文字
  final String? cancelBtnTooltip;

  const KqSearchBar(
      {Key? key,
      this.hintText,
      this.onSubmit,
      this.onCancel,
      this.onTap,
      this.onMonitor,
      this.onChanged,
      this.autofocus = false,
      this.customLeftIcon,
      this.textColor,
      this.placeHolderTextColor,
      this.cancelTextColor,
      this.searchIconColor,
      this.outerBgColor,
      this.fontSize,
      this.innerBgColor,
      this.cursorColor,
      this.onCleared,
      this.newValue,
      this.paddingLeft,
      this.paddingRight,
      this.outHeight,
      this.innerHeight,
      this.unFocusWhenCleared = false,
      this.alwaysShowCancelBtn = false,
      this.showDivider = false,
      this.cancelBtnEnable = true,
      this.autoFocusBorder = false,
      this.enablePDAScan = false,
      this.editController,
      this.customLeftWidget,
      this.customRightWidget,
      this.cancelBtnTooltip,
      this.editable = true})
      : super(key: key);

  @override
  KqSearchBarState createState() => KqSearchBarState();
}

class KqSearchBarState extends State<KqSearchBar> {
  /// 全局焦点
  final FocusNode _globalFocusNode = FocusNode();

  /// 搜索框控制器
  late TextEditingController _editingController;

  bool _cancelVisible = false;

  @override
  void initState() {
    _editingController =
        widget.editController ?? TextEditingController(text: '');
    super.initState();
  }

  /// 设置搜索内容
  updateSearchText(String value) {
    _editingController.text = value;
  }

  /// 获取搜索内容
  getSearchText() {
    return _editingController.text;
  }

  /// 当前是有扫码枪焦点
  bool isFocused() {
    return _globalFocusNode.hasFocus;
  }

  /// 显示焦点边框
  requestFocus() {
    _globalFocusNode.requestFocus();
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    _globalFocusNode.dispose();
  }

  /// 开始搜索
  void _handleScanContent(content) {
    if (widget.onSubmit != null) {
      widget.onSubmit!(content, this);
    }
  }

  @override
  void didUpdateWidget(covariant KqSearchBar oldWidget) {
    if (widget.editController != null &&
        widget.editController != _editingController) {
      _editingController =
          widget.editController ?? TextEditingController(text: '');
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    if (!widget.enablePDAScan) {
      //这里强制不使用pda扫码监听，防止模拟器点击回车也触发onSubmit
      return _buildSearchBar();
    }
    return KqRawKeyboardListener(
        autofocus: widget.editable || widget.autoFocusBorder,
        focusNode: _globalFocusNode,
        onScanCallback: (scanContent) {
          _handleScanContent(scanContent);
        },
        child: _buildSearchBar());
  }

  _buildSearchBar() {
    return InkWell(
      onTap: widget.editable
          ? null
          : () {
              widget.onTap?.call(this);
            },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            color: widget.outerBgColor ?? KqThemeColors.bgWhite,
            width: double.infinity,
            height: widget.outHeight ?? 44.r,
            padding: EdgeInsets.only(
              left: widget.paddingLeft ?? 16.r,
              right: widget.paddingRight ?? 16.r,
            ),
            child: Row(
              children: [
                /// 左侧自定义布局
                widget.customLeftWidget ?? Container(),

                /// 搜索框+清空按钮部分
                Expanded(
                  child: Container(
                    width: double.infinity,
                    height: widget.innerHeight ?? 30.r,
                    decoration: BoxDecoration(
                        color: widget.innerBgColor ?? KqThemeColors.bgF4,
                        border: ((widget.enablePDAScan &&
                                        _globalFocusNode.hasFocus ||
                                    widget.autoFocusBorder) &&
                                !widget.editable)
                            ? Border.all(
                                width: 1,
                                color: KqThemeManager.getCommonConfig()
                                        .mainColor ??
                                    KqThemeColors.bgBlue)
                            : null,
                        borderRadius: BorderRadius.circular(4.r)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        SizedBox(
                          width:
                              widget.innerBgColor == KqThemeColors.bgTransparent
                                  ? 0
                                  : 12.r,
                          height: 1,
                        ),
                        widget.customLeftIcon ??
                            SizedBox(
                              width: 16.r,
                              height: 16.r,
                              child: Image.asset(
                                Images.commonIcSearch16,
                                fit: BoxFit.fill,
                                color: widget.searchIconColor,
                                package: KqGlobal.packageName,
                              ),
                            ),
                        SizedBox(
                          width: 8.r,
                          height: 1,
                        ),
                        Expanded(
                          child: KqTextFiled(
                            controller: _editingController,
                            textInputAction: TextInputAction.search,
                            placeHolder: widget.hintText ??
                                KqIntl.currentResource.search,
                            forceShowPlaceHolder: true,
                            editable: widget.editable,
                            enableClearButton: !kIsWeb &&
                                (Platform.isAndroid || Platform.isIOS),
                            fontSize: widget.fontSize ?? 14.sp,
                            newValue: widget.newValue,
                            unFocusWhenCleared: widget.unFocusWhenCleared,
                            textColor: widget.textColor,
                            placeHolderTextColor: widget.placeHolderTextColor,
                            cursorColor: widget.cursorColor,
                            autofocus: widget.autofocus,
                            onSubmitted: (text) {
                              _handleScanContent(text);
                            },
                            onCleared: () {
                              if (widget.onCleared != null) {
                                widget.onCleared!();
                              } else {
                                _handleScanContent("");
                              }
                            },
                            onChanged: widget.onChanged,
                            onMonitor: widget.onMonitor,
                            onFocusChanged: (hasFocus) {
                              if (!hasFocus && widget.enablePDAScan) {
                                _globalFocusNode.requestFocus();
                              }
                              setState(() {
                                _cancelVisible = hasFocus;
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                /// 取消按钮
                Visibility(
                    visible: widget.alwaysShowCancelBtn ||
                        (widget.cancelBtnEnable && _cancelVisible),
                    child: Row(
                      children: [
                        SizedBox(
                          width: 8.r,
                          height: 1,
                        ),
                        KqInkWell(
                          radius: 4.r,
                          horizontalPadding: 8.r,
                          tooltip: widget.cancelBtnTooltip,
                          onTap: () {
                            if (widget.enablePDAScan) {
                              _globalFocusNode.requestFocus();
                            } else {
                              TextFiledUtil.clearFocus(context);
                            }
                            _editingController.text = '';
                            widget.onCancel?.call();
                          },
                          child: Container(
                            height: widget.innerHeight ?? 30.r,
                            alignment: Alignment.center,
                            child: Text(
                              KqIntl.currentResource.cancel,
                              style: TextStyle(
                                  fontSize: widget.fontSize ?? 14.sp,
                                  color: widget.cancelTextColor ??
                                      KqThemeManager.getCommonConfig()
                                          .mainLightColor ??
                                      KqThemeColors.textLightBlue),
                            ),
                          ),
                        )
                      ],
                    )),

                /// 右侧自定义布局
                widget.customRightWidget ?? Container(),
              ],
            ),
          ),
          Visibility(visible: widget.showDivider, child: const KqDivider())
        ],
      ),
    );
  }
}
